package com.ruge.user.service.impl;

import com.ruge.core.response.Response;
import com.ruge.core.tool.RedisKeyTool;
import com.ruge.user.domain.request.BlobOperaRequest;
import com.ruge.user.service.BlobOperaService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author ruge.wu
 * @since 2021/12/27 15:58
 */
@Service
public class BlobOperaServiceImpl implements BlobOperaService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 点赞
     *
     * @param request {@link BlobOperaRequest}
     * @return {@link Response}
     */
    @Override
    public Response like(BlobOperaRequest request) {
        Long aid = request.getAid();
        Long blobId = request.getBlobId();
        String blogKey = RedisKeyTool.buildBlogKey(blobId);
        redisTemplate.opsForSet().add(blogKey, aid, System.currentTimeMillis());
        return Response.create();
    }

    /**
     * 取消点赞
     *
     * @param request {@link BlobOperaRequest}
     * @return {@link Response}
     */
    @Override
    public Response unLike(BlobOperaRequest request) {
        Long aid = request.getAid();
        Long blobId = request.getBlobId();
        String blogKey = RedisKeyTool.buildBlogKey(blobId);
        redisTemplate.opsForSet().remove(blogKey, aid);
        return Response.create();
    }

    /**
     * 校验用户是否已点赞
     *
     * @param request {@link BlobOperaRequest}
     * @return {@link Response}
     */
    @Override
    public Response checkLike(BlobOperaRequest request) {
        Long aid = request.getAid();
        Long blobId = request.getBlobId();
        String blogKey = RedisKeyTool.buildBlogKey(blobId);
        Boolean member = redisTemplate.opsForSet().isMember(blogKey, aid);
        return Response.create(member);
    }

    /**
     * 返回点赞的用户列表，用户数量
     *
     * @param request {@link BlobOperaRequest}
     * @return {@link Response}
     */
    @Override
    public Response getLikeInfo(BlobOperaRequest request) {
        Long aid = request.getAid();
        Long blobId = request.getBlobId();
        String blogKey = RedisKeyTool.buildBlogKey(blobId);
        Set members = redisTemplate.opsForSet().members(blogKey);
        Long size = redisTemplate.opsForSet().size(blogKey);
        Map<String, Object> blogOperaInfo = new HashMap<>();
        blogOperaInfo.put("members", members);
        blogOperaInfo.put("size", size);
        return Response.create(blogOperaInfo);
    }
}
